#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题: 字节到大整数的打包与解包
问题: 你有一个字节字符串并想将它解压成一个整数。或者，你需要将一个大整数转换为一个字节字符串。
提示 : 
    1. 字节顺序规则(little或big)仅仅指定了构建整数时的字节的低位高位排列方式
"""

def recipe1():
    """将bytes解析为整数"""
    data = b'\x00\x124V\x00x\x90\xab\x00\xcd\xef\x01\x00#\x004'
    print(f"{data = }")
    print(f"{len(data) = }")
    print(f"{int.from_bytes(data, 'little') = }")
    print(f"{int.from_bytes(data, 'big') = }")

def recipe2():
    """将一个大整数转换为一个字节字符串，使用 int.to_bytes() 方法"""
    x = 94522842520747284487117727783387188
    print(f"{x = }")
    print(f"{x.to_bytes(16, 'big') = }")
    print(f"{x.to_bytes(16, 'little') = }")

def recipe3():
    # bit_length真有用
    x = 523 ** 23
    print(f"{x = }")
    print(f"{x.bit_length() = }")
    # print(f"{x.to_bytes(16, 'little') = }")  # OverflowError
    nbytes, rem = divmod(x.bit_length(), 8) # 把除数和余数运算结果结合起来,返回一个包含商和余数的元组
    if rem:
        nbytes += 1
    print(f"{x.to_bytes(nbytes, 'little') = }")    

def main():
    print('recipe1'.center(20, '*'))
    recipe1() 
    print('recipe2'.center(20, '*'))
    recipe2() 
    print('recipe3'.center(20, '*'))
    recipe3() 

if __name__ == '__main__':
    main()       